package com.cj.dubbo.protocool.http;

import com.alibaba.fastjson.JSONObject;
import com.cj.dubbo.framework.Invocation;
import com.cj.dubbo.localRegist.LocalRegister;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author chan
 * @dateTime 2022/9/28  14:05:55
 * 请求处理
 */
public class HttpServerHandler extends HttpServlet {

    @Override
    public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Invocation invocation = JSONObject.parseObject(req.getInputStream(), Invocation.class);
        //本地注册获取到类信息，反射调用方法
        Class aClass = LocalRegister.get(invocation.getInterfaceName());

        try {
            Method method = aClass.getMethod(invocation.getMethodName(), invocation.getParamTypes());
            if (method != null) {
                method.setAccessible(true);
                String methodResult = (String) method.invoke(aClass.newInstance(), invocation.getParams());
//                IOUtils.write(methodResult, resp.getOutputStream());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
